<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件操作接口演示</title>
    <style>
        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            font-family: 'Segoe UI', system-ui;
        }

        .operation-section {
            margin-bottom: 30px;
            padding: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        input,
        button {
            padding: 8px 12px;
            margin: 5px 0;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }

        .result-area {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 文件上传模块 -->
        <div class="operation-section">
            <h3>文件上传</h3>
            <div class="form-group">
                <input type="file" id="fileInput">
                <button onclick="handleUpload()">上传文件</button>
            </div>
            <div class="result-area" id="uploadResult"></div>
        </div>

        <!-- 文件创建模块 -->
        <div class="operation-section">
            <h3>创建新文件</h3>
            <div class="form-group">
                <input type="text" id="fileType" placeholder="输入文件夹名称">
                <textarea id="fileContent" placeholder="输入文件内容"></textarea>
                <button onclick="createNewFile()">创建文件</button>
            </div>
            <div class="result-area" id="createResult"></div>
        </div>

        <!-- 文件追加模块 -->
        <div class="operation-section">
            <h3>追加文件内容</h3>
            <div class="form-group">
                <input type="text" id="fileName" placeholder="输入文件名">
                <textarea id="appendContent" placeholder="输入追加内容"></textarea>
                <button onclick="appendToFile()">追加内容</button>
            </div>
            <div class="result-area" id="appendResult"></div>
        </div>
    </div>

    <script>
        (function () {
            login()
        }())
        var token = ''
        function login() {
            fetch('http://localhost:3300/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: 'admin',
                    password: '123456'
                })
            }).then(res => res.json()).then(res => {
                console.log('登录成功，token：', res.data.token);
                if (res.code === 200 && res.data.token) {
                    token = res.data.token
                }
            })
        }
        // 通用请求处理函数
        async function sendRequest(url, method, body) {
            try {
                const response = await fetch(`http://localhost:3300${url}`, {
                    method: method,
                    headers: { 'Content-Type': 'application/json', 'Authorization': token },
                    body: JSON.stringify(body)
                });
                return await response.json();
            } catch (error) {
                return { error: '请求失败: ' + error.message };
            }
        }

        // 文件上传处理
        async function handleUpload() {
            const fileInput = document.getElementById('fileInput');
            const resultArea = document.getElementById('uploadResult');

            if (!fileInput.files[0]) {
                resultArea.innerHTML = '请先选择要上传的文件';
                return;
            }

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            try {
                const response = await fetch('http://localhost:3300/api/upload', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                resultArea.innerHTML = data.success
                    ? `文件上传成功！路径：${data.path}`
                    : '文件上传失败';
            } catch (error) {
                resultArea.innerHTML = '上传请求失败: ' + error.message;
            }
        }

        // 创建新文件
        async function createNewFile() {
            const [type, content] = [
                document.getElementById('fileType').value.trim(),
                document.getElementById('fileContent').value.trim()
            ];
            const resultArea = document.getElementById('createResult');

            if (!type || !content) {
                resultArea.innerHTML = '请填写完整信息';
                return;
            }

            const response = await sendRequest('/api/createFile', 'POST', {
                fileType: type,
                content: content
            });
            resultArea.innerHTML = response.code === 200
                ? `文件创建成功！路径：${response.data.path}`
                : `创建失败：${response.message}`;
        }

        // 追加文件内容
        async function appendToFile() {
            const [name, content] = [
                document.getElementById('fileName').value.trim(),
                document.getElementById('appendContent').value.trim()
            ];
            const resultArea = document.getElementById('appendResult');

            if (!name || !content) {
                resultArea.innerHTML = '请填写完整信息';
                return;
            }

            const response = await sendRequest('/api/writeFile', 'POST', {
                filename: name,
                content: content
            });
            resultArea.innerHTML = response.code === 200
                ? `内容追加成功！文件大小：${response.data.size}字节`
                : `操作失败：${response.message}`;
        }
    </script>
</body>

</html>